package com.betterwood.dragon.service;

import java.time.LocalDateTime;
import java.util.List;

import com.betterwood.dragon.dao.ChangeDao;
import com.betterwood.dragon.dao.ResultDao;
import com.betterwood.dragon.entity.Change;
import com.betterwood.dragon.entity.Keyword;
import com.betterwood.dragon.entity.Product;
import com.betterwood.dragon.entity.Record;
import com.betterwood.dragon.entity.Result;
import com.betterwood.dragon.entity.Site;
import com.betterwood.dragon.entity.dto.SearchDTO;
import com.betterwood.dragon.utils.RedisUtil;
import com.betterwood.dragon.utils.TimeUtil;
import com.betterwood.dragon.worms.BLY;
import com.betterwood.dragon.worms.DZ;
import com.betterwood.dragon.worms.FJ;
import com.betterwood.dragon.worms.HZ;
import com.betterwood.dragon.worms.JF;
import com.betterwood.dragon.worms.JZT;
import com.betterwood.dragon.worms.RY;
import com.betterwood.dragon.worms.YF;
import com.betterwood.dragon.worms.ZK;
import com.microsoft.playwright.*;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import cn.hutool.core.util.NumberUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;

import lombok.RequiredArgsConstructor;
import lombok.extern.log4j.Log4j2;
import lombok.extern.slf4j.Slf4j;

import static org.joor.Reflect.*;

@Slf4j
@Service(value = "wormNest")
@RequiredArgsConstructor
public class WormNest {
    private final ResultDao resultDao;

    @Async
    public void wormGate(Site site, SearchDTO search) {
        if (site.getStatus() == 1) {
            String msg = "************Site:" + site.getSiteNo() + " IS NOT ONLINE SKIPPING***********";
            log.info(msg);
            return;
        }
        String siteNo = site.getSiteNo();
        // String siteNo = "DZ";
        String className = "com.betterwood.dragon.worms." + siteNo;
        log.info("************");
        log.info(className);
        List<Result> res = onClass(className).create().call("fetchProduct", site, search).get();
        // List<Result> res = BLY.fetchProduct(site, search);
        String resultMsg = "**********FETCH " + Integer.toString(res.size()) + " RESULTS FROM " + site.getSiteName()
                + "*************";
        log.info(resultMsg);
        resultDao.insertResults(res);
    }

    @Async
    public void wormGateTest(Site site, SearchDTO search) {
        if (site.getStatus() == 1) {
            log.info("SITE IS NOT ONLINE, EXIT");
            return;
        }

        List<Result> res = JF.fetchProduct(site, search);

        // resultDao.insertResults(res);
        // log.info(res);
    }

}
